/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.knowledge.doc.controller;

import com.wallellen.core.page.ViewMode;
import com.wallellen.knowledge.doc.domain.Docfile;
import com.wallellen.knowledge.doc.server.FileManagerInter;
import com.wallellen.parameter.ParamService;
import com.wallellen.web.WebUtils;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 文档管理
 *
 * @author <a href="mailto:wallellen@hotmail.com">WALLE</a>
 */
@RequestMapping("/actionImg")
@Controller
public class ActionImgQuery extends WebUtils {
    private static final Logger log = LoggerFactory.getLogger(ActionImgQuery.class);
    // private File imgFile;
    // private int error;
    // private String url;
    // private String message;
    // private InputStream inputStream;
    // private String id;
    // private String filename;
    // private String imgFileFileName;
    // private String imgFileContentType;

    @Resource
    private FileManagerInter fileManagerImpl;

    //
    // @Override
    // public void addActionError(String anErrorMessage) {
    // // 这里要先判断一下，是我们要替换的错误，才处理
    // if (anErrorMessage
    // .startsWith("Request exceeded allowed size limit! Max size allowed is"))
    // {
    // Pattern pattern = Pattern.compile("[,|\\d]+");
    // Matcher m = pattern.matcher(anErrorMessage);
    // // 匹配一次
    // m.find();
    // String s1 = m.group().replaceAll(",", "");// 上传的文件大小
    // // 再匹配一次
    // m.find();
    // String s2 = m.group().replaceAll(",", "");// 所限制的大小
    // String fileUploadErrorMessage = null;
    // if (!s1.equals("") && !s2.equals("")) {
    // fileUploadErrorMessage = "你上传的文件大小（" + Long.valueOf(s2) / 1024
    // / 1024 + "M）超过允许的大小（" + Long.valueOf(s1) / 1024 / 1024
    // + "M）";
    // getRequest().setAttribute("fileUploadErrorMessage",
    // fileUploadErrorMessage);
    // // 将信息替换掉
    // super.addActionError(fileUploadErrorMessage);
    // }
    // } else {// 否则按原来的方法处理
    // super.addActionError(anErrorMessage);
    // }
    // }
    //

    /**
     * 上传文件
     *
     * @return
     */
    @RequestMapping(value = "/PubFPupload.do")
    @ResponseBody
    public Map<String, Object> upload(@RequestParam(value = "imgFile", required = false) MultipartFile file,
                                      HttpServletRequest request, ModelMap model, HttpSession session) {
        int error;
        String message;
        String url = null;
        String id = null;
        String fileName = "";
        try {
            String fileid = null;
            // 验证大小
            String maxLength = ParamService.getInstance().getParameter("config.doc.upload.length.max");
            if (file.getSize() > Integer.valueOf(maxLength)) {
                throw new Exception("文件不能超过" + Integer.valueOf(maxLength) / 1024 + "kb");
            }
            CommonsMultipartFile cmFile = (CommonsMultipartFile) file;
            DiskFileItem item = (DiskFileItem) cmFile.getFileItem();
            {//小于8k不生成到临时文件，临时解决办法。zhanghc20150919
                if (!item.getStoreLocation().exists()) {
                    item.write(item.getStoreLocation());
                }
            }

            fileName = URLEncoder.encode(item.getName(), "utf-8");
            // 验证类型
            List<String> types = parseIds(ParamService.getInstance().getParameter("config.doc.upload.types")
                    .toUpperCase().replaceAll("，", ","));
            if (!types.contains(file.getOriginalFilename()
                    .substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length())
                    .toUpperCase())) {
                throw new Exception("文件类型错误，允许的类型为：" + ParamService.getInstance()
                        .getParameter("config.doc.upload.types").toUpperCase().replaceAll("，", ","));
            }
            fileid = fileManagerImpl.saveFile(item.getStoreLocation(), FileManagerInter.FILE_TYPE.HTML_INNER_IMG,
                    file.getOriginalFilename(), getCurrentUser(session));
            error = 0;
            url = fileManagerImpl.getFileURL(fileid);
            message = "";
            id = fileid;
        } catch (Exception e) {
            e.printStackTrace();
            error = 1;
            message = e.getMessage();
        }
        return ViewMode.getInstance()
                .putAttr("error", error)
                .putAttr("url", url)
                .putAttr("message", message)
                .putAttr("id", id)
                .putAttr("fileName", fileName)
                .returnObjMode();
    }

    /**
     * 下载文件
     *
     * @return
     */
    @RequestMapping("/Publoadfile")
    public void download(String id, HttpServletRequest request, HttpServletResponse response) {
        Docfile file = null;
        try {
            file = fileManagerImpl.getFile(id);
        } catch (Exception e) {
            file = null;
        }
        if (file == null || file.getFile() == null || !file.getFile().exists()) {
            file = new Docfile();
            file.setFile(fileManagerImpl.getNoneImg());
            file.setName("none");
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        try {
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("gbk"), "iso-8859-1"));
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        try {
            InputStream is = new FileInputStream(file.getFile());
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
            // 这里主要关闭。
            os.close();
            is.close();
        } catch (FileNotFoundException e) {
            try {
                String webPath = ParamService.getInstance().getParameter("farm.constant.webroot.path");
                String filePath = "/WEB-FACE/img/style/nullImg.png".replaceAll("/",
                        File.separator.equals("/") ? "/" : "\\\\");
                File nullFile = new File(webPath + filePath);
                InputStream is = new FileInputStream(nullFile);
                OutputStream os = response.getOutputStream();
                byte[] b = new byte[2048];
                int length;
                while ((length = is.read(b)) > 0) {
                    os.write(b, 0, length);
                }
                // 这里主要关闭。
                os.close();
                is.close();
            } catch (Exception e1) {
                log.error(e.getMessage());
            }
            log.error(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // private final static FarmFileManagerInter fileIMP =
    // (FarmFileManagerInter) BeanFactory
    // .getBean("farm_docFileProxyId");
    //
    // public File getImgFile() {
    // return imgFile;
    // }
    //
    // public void setImgFile(File imgFile) {
    // this.imgFile = imgFile;
    // }
    //
    // public int getError() {
    // return error;
    // }
    //
    // public void setError(int error) {
    // this.error = error;
    // }
    //
    // public String getUrl() {
    // return url;
    // }
    //
    // public void setUrl(String url) {
    // this.url = url;
    // }
    //
    // public String getMessage() {
    // return message;
    // }
    //
    // public void setMessage(String message) {
    // this.message = message;
    // }
    //
    // public InputStream getInputStream() {
    // return inputStream;
    // }
    //
    // public void setInputStream(InputStream inputStream) {
    // this.inputStream = inputStream;
    // }
    //
    // public String getId() {
    // return id;
    // }
    //
    // public void setId(String id) {
    // this.id = id;
    // }
    //
    // public String getFilename() {
    // try {
    // filename = new String(filename.getBytes("GBK"), "ISO-8859-1");
    // } catch (UnsupportedEncodingException e) {
    //
    // }// 中文乱码解决
    // return filename;
    // }
    //
    // public void setFilename(String filename) {
    // this.filename = filename;
    // }
    //
    // public String getImgFileFileName() {
    // return imgFileFileName;
    // }
    //
    // public void setImgFileFileName(String imgFileFileName) {
    // this.imgFileFileName = imgFileFileName;
    // }
    //
    // public String getImgFileContentType() {
    // return imgFileContentType;
    // }
    //
    // public void setImgFileContentType(String imgFileContentType) {
    // this.imgFileContentType = imgFileContentType;
    // }

}
